<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        body{
            text-align: center;
            background: #000;
        }
        #c1{
            background: #fff;
        }
    
    </style>
</head>
<body onload="init()">
    <canvas id="c1" width="800" height="600"></canvas>
</body>
<script>
    class Figure{
        constructor(sx,sy,sw,sh,dx,dy,dw,dh,img_src){
            this.sx=sx;
            this.sy=sy;
            this.sw=sw;
            this.sh=sh;
            this.dx=dx;
            this.dy=dy;
            this.dw=dw;
            this.dh=dh;
            let img = new Image();
            img.src = img_src;
            this.img = img;
        }
        draw(){
            oC.drawImage(this.img, this.sx, this.sy,this.sw, this.sh,this.dx,this.dy,this.dw,this.dh);
        }
    }
    let time;
    let oC=document.getElementById('c1').getContext('2d');
    let dnf=new Figure(56,35,153,167,100,100,153,167,'timg.jpg');
    let i=0;
    let speed=10;
    function init(){
        drawAll();
        time=setInterval(drawAll,100);
    }
    let d = 'l';
    function drawAll(){
        oC.clearRect(0,0,800,600);
        dnf.sx=56+i*210
        // dnf.dx-=speed
        document.onkeyup=keyup;
        dnf.draw();
        i++;
        if(i==4){
            i=0;
        }
        if(d=='l'){
            dnf.dx-=speed
        }else{
            dnf.dx+=speed
        }
    }
    let key=37;
    function keyup(ev){
        if(ev.keyCode==37){
            dnf.sy=35
            d='l'
        }else if(ev.keyCode==39){
            dnf.sy=454
            d='r'
        }
    }
</script>
</html>